package com.compty.paint.manager;

import java.util.List;

import org.hibernate.SQLQuery;
import org.hibernate.Session;

import com.compty.core.hibernate.HibernateEntityDao;
import com.compty.paint.domain.AddressInfo;
import com.compty.paint.domain.CustomerInfo;

/**
 *会员收货地址管理
 */
public class AddressInfoManager extends HibernateEntityDao<AddressInfo> {

	/**
	 * 列出会员所有收货地址
	 * @param customerInfo 会员客户
	 */
	@SuppressWarnings("unchecked")
	public List<AddressInfo> findByCustomerInfo(CustomerInfo customerInfo) {
		String hql = "from AddressInfo where customerInfo=? order by defaultFlag desc,id desc";
		return super.find(hql, customerInfo);
	}
	
	/**
	 * 会员名下收货地址数量
	 * @param customerInfo
	 */
	public int findCountByCustomerInfo(CustomerInfo customerInfo) {
		String hql = "select count(*) from AddressInfo where customerInfo=? order by defaultFlag desc,id desc";
		return super.getCount(hql, customerInfo);
	}

	/**
	 * 是否将地址设为默认地址
	 * @param addressId 地址ID
	 * @param defaultFlag 默认状态标识(1:默认，0：非默认地址)
	 */
	public void setDefaultAddress(CustomerInfo customerInfo,Integer addressId, String defaultFlag) {
		if( "1".equals(defaultFlag)){
			
			Long cId = customerInfo.getId();
			Session session = getSession();
			SQLQuery sqlQuery = session.createSQLQuery("update t_addressinfo set default_flag = '0' where customer_id=? and id <>?");
			sqlQuery.setParameter(0, cId);
			sqlQuery.setParameter(1, addressId);
			sqlQuery.executeUpdate();
			
			sqlQuery = session.createSQLQuery("update t_addressinfo set default_flag = '1' where customer_id=? and id = ?");
			sqlQuery.setParameter(0, cId);
			sqlQuery.setParameter(1, addressId);
			sqlQuery.executeUpdate();
			
		}else{
			AddressInfo addressInfo = get(addressId);
			addressInfo.setDefaultFlag(defaultFlag);
			
			save(addressInfo);
		}
	}

}
